<template>
    <div>
        <el-select v-model="value" autocomplete="off" filterable remote reserve-keyword placeholder="请输入公司名称搜索"
            :remote-method="querySearchAsync" :loading="loading">
            <el-option v-for="item in list" :key="item.id" :label="item.company" :value="item.id">
            </el-option>
        </el-select>
        <el-button v-show="props.btn" type="primary" @click="handleSelect">切换公司</el-button>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { apiCompanyLists } from '@/api/company'
import cache from '@/utils/cache'
import feedback from '@/utils/feedback'
// 使用 `defineProps` 定义 props
const props = defineProps({
    btn: {
        type: Boolean,
        default: true
    }
});
const emits = defineEmits(['isOk']);
const value = ref('');
const list = ref([]);
const loading = ref(false);
watch(() => value.value, (v: any) => {
    if (v) {
        let name = list.value.find(function (item) {
            return item.id === v;
        });
        let companyInfo = {
            companyId: v,
            companyName: name.company
        }
        emits('isOk', companyInfo)
    }
})
const querySearchAsync = (queryString: string) => {
    loading.value = true
    let data = {
        page_no: 1,
        page_size: 15,
        company: queryString
    }
    apiCompanyLists(data).then((res) => {
        list.value = res.lists
    }).finally(() => {
        loading.value = false
    })
}
const handleSelect = (item: any) => {
    let result = list.value.find(item => item.id === value.value);
    cache.set('company', result)
    feedback.alertSuccess('切换成功')
}
const getLocalItem = () => {
    if (!props.btn) { return }
    let item = cache.get('company')
    if (item?.id) {
        list.value = [item]
        value.value = item.id
    }
}
getLocalItem()
</script>